package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * @author 于金鹏
 * @Date 2024/12/23 18:42
 * @Package StudentCheckSystem
 */
@WebFilter("/*")
public class LoginTimeoutFilter implements Filter {
    private static final long LOGIN_TIMEOUT_MILLIS = 10 * 1000L;
    ; // 30分钟换算为毫秒数

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        HttpSession session = req.getSession();
        if (req.getServletPath().equals("/userlogin")) {
            filterChain.doFilter(req, resp);
        }
        else if (session.getAttribute("loginTime") == null) {
            // 用户未登录，返回错误信息或重定向到登录页面
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write("{\"code\":401,\"msg\":\"请先登录\"}");
        } else {
            // 用户已登录，放行请求
            filterChain.doFilter(req, resp);
        }
        // 登录未超时，放行请求，让请求继续向后执行
//        filterChain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
    }
}
